import { createRouter, createWebHashHistory } from "vue-router";
import { userStore } from "@/stores/userStore";
import user from "@/services/user.js";
import { dateEquals, ElMessage } from "element-plus";
import component from "element-plus/es/components/tree-select/src/tree-select-option.mjs";

// 制定路由规则
const routes = [
  {
    path: "/",
    component: () => import("@/views/Main.vue"),
    redirect: "/home",
    name: "main",
  },


  {
    component: () => import("@/views/Main.vue"),
    name: "main",
    children: [
        {
          path: '/personal/center',
          name: 'personalCenter',
          label: '个人中心',
          component: () => import("@/views/PersonalCenter.vue")
        }
    ]
  },
  {
    path: "/login",
    name: "login",
    label: "登录",
    component: () => import("@/views/Login.vue"),
  }
];

const router = createRouter({
  // 设置路由模式
  history: createWebHashHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  const store = userStore();
  const res = await user.getCurrentUser();
  if (res.code !== 200 && to.path !== "/login") {
    localStorage.removeItem('userState')
    next("/login");
  } else {
    if (res.code === 200 && !localStorage.getItem("userState")) {
      store.state.loginUserInfo = res.data;
      store.state.menuCodes = res.data.menuCodes;
      store.menuRoute(router);
      store.state.loginUserInfo.currentTime = new Date().toLocaleString()
    }
     next();
  }
  
});

export default router;
